import axios, { AxiosRequestConfig, Method } from 'axios'

// 定义请求接口
interface PendingType {
	url?: string;
	method?: Method;
	data?: object;
	cancel: Function;
}
// 正在请求的ajax数组
const pending: Array<PendingType> = []
// 取消接口
const CancelToken = axios.CancelToken
// 初始化实例
const instance = axios.create({
	timeout: 10
})
// 删除正在请求
const removePending = (config: AxiosRequestConfig) => {
	for (const key in pending) {
		const index: number = +key;
		const item: PendingType = pending[index]
		if (item.url === config.url && item.method === config.method && item.data === config.data) {
			item.cancel('操作过于频繁')
			pending.splice(index, 1)
		}
	}
}


//请求拦截器
instance.interceptors.request.use(config => {
	//发起请求时，取消掉当前正在进行的相同请求
	removePending(config)
	config.cancelToken = new CancelToken((c) => {
		pending.push({ url: config.url, method: config.method, data: config.data, cancel: c });
	});
	return config
}, error => {
	return Promise.reject(error)
})
// 响应拦截器
instance.interceptors.response.use(response => {
	removePending(response.config)
	const httpCode = response.data.httpCode
	switch (httpCode) {
		case '401':
			break
		case '500':
			break
		default:
			break
	}
	return response
}, err => {
	if (err && err.response) {
		switch (err.response.status) {
			case 401:
				err.message = '未授权，请重新登录'
				break;
			case 404:
				err.message = '请求错误,未找到该资源,404.'
				break;
			case 500:
				err.message = '服务器端出错'
				break;
			default:
				err.message = `连接错误${err.response.status}`
		}
	} else {
		if (err.code === 'ECONNABORTED' || err.message === 'Network Error') {
			err.message = '请求超时'
		}
	}
	return Promise.resolve(err)
})

export default {
	get(url: string, param?: object) {
		return instance({
			method: 'get',
			url,
			headers: {},
			params: param
		})
	},
	post(url: string, param?: object) {
		return axios({
			method: 'post',
			url,
			headers: {},
			data: param
		})
	},
}

